package com.mk.admin.service.impl;

import com.mk.admin.mapper.DoctorLikesMapper;
import com.mk.admin.mapper.DoctorMapper;
import com.mk.admin.model.ResultDto;
import com.mk.admin.model.dto.DoctorLikesDto;
import com.mk.admin.model.entity.DoctorEntity;
import com.mk.admin.model.entity.DoctorLikesEntity;
import com.mk.admin.model.query.DoctorLikesQuery;
import com.mk.admin.model.vo.DoctorLikesVo;
import com.mk.admin.service.DoctorLikesService;
import com.mk.admin.service.DoctorService;
import com.mk.admin.util.DateTool;
import com.mk.admin.util.JSONCopy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DoctorLikesServiceImpl implements DoctorLikesService {
    @Autowired
    private DoctorLikesMapper doctorLikesMapper;
    @Autowired
    private DoctorMapper doctorMapper;

    @Override
    public ResultDto select(DoctorLikesQuery query) {
        DoctorLikesEntity entity = JSONCopy.copy(query, DoctorLikesEntity.class);
        return ResultDto.data(doctorLikesMapper.count(entity), doctorLikesMapper.select(entity));
    }

    @Transactional
    @Override
    public ResultDto add(DoctorLikesVo doctorLikesVo) {
        DoctorLikesEntity entity = JSONCopy.copy(doctorLikesVo, DoctorLikesEntity.class);
        DoctorEntity doctorEntity = new DoctorEntity();
        doctorEntity.setNum(doctorLikesVo.getNum());
        doctorEntity.setId(doctorLikesVo.getDoctorId());
        try {
            doctorMapper.likesNum(doctorEntity);
//            查看收藏表里面是否有值，如果有，则新增，否则修改
            List<DoctorLikesDto> list = doctorLikesMapper.select(entity);
            if (list.size() == 0) {
                entity.setCreateTime(DateTool.format());
                entity.setStatus(1);
                doctorLikesMapper.insert(entity);
            } else {
                entity.setId(list.get(0).getLikesId());
                entity.setUpdateTime(DateTool.format());
                entity.setStatus(doctorLikesVo.getNum() == 1 ? 1 : 0);
                doctorLikesMapper.updateById(entity);
            }
            return ResultDto.data("success");
        } catch (Exception e) {
            return ResultDto.data("error");
        }
    }

    @Override
    public ResultDto update(DoctorLikesVo doctorLikesVo) {
        DoctorLikesEntity entity = JSONCopy.copy(doctorLikesVo, DoctorLikesEntity.class);
        return ResultDto.data(doctorLikesMapper.updateById(entity));
    }

    @Override
    public ResultDto delete(int id) {
        return ResultDto.data(doctorLikesMapper.deleteById(id));
    }

    @Override
    public ResultDto status(int id) {
        return ResultDto.data(doctorLikesMapper.status(id));
    }
}
